package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.EnterpriseOutfallValveInfoMapper;
import com.bf.electroplating.mapper.EnterpriseOutfallValveMapper;
import com.bf.electroplating.pojo.dto.OutfallMonitoringQueryDTO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallMonitoringData;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallValve;
import com.bf.electroplating.pojo.entity.EnterpriseOutfallValveInfo;
import com.bf.electroplating.pojo.vo.*;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.IEnterpriseOutfallService;
import com.bf.electroplating.service.IEnterpriseOutfallValveService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业排污口服务实现类
 *
 * @author system
 * @since 2025-01-11
 */
@Slf4j
@Service
public class EnterpriseOutfallServiceImpl extends ServiceImpl<EnterpriseOutfallValveInfoMapper, EnterpriseOutfallValveInfo> implements IEnterpriseOutfallService {

    @Autowired
    private com.bf.electroplating.service.IEnterpriseOutfallMonitoringDataService monitoringDataService;
    @Resource
    private IEnterpriseOutfallValveService enterpriseOutfallValveService;
    @Resource
    private ComCompanyService comCompanyService;

    @Override
    public OutfallMonitoringDialogVO getOutfallMonitoringDialogData(OutfallMonitoringQueryDTO queryDTO) {
        log.info("获取排污口监测弹框数据，查询条件: {}", queryDTO);

        OutfallMonitoringDialogVO result = new OutfallMonitoringDialogVO();

        try {
            // 1. 获取当前数据（雷达图数据）
            List<OutfallRadarDataVO> currentData = getCurrentRadarData();
            result.setCurrentData(currentData);

            // 2. 获取历史数据
            Page<OutfallMonitoringDataVO> historyDataPage = getHistoryData(queryDTO);
            result.setHistoryData(historyDataPage.getRecords());
            result.setTotal(historyDataPage.getTotal());
            result.setCurrentPage((int) historyDataPage.getCurrent());
            result.setPageSize((int) historyDataPage.getSize());
            result.setTotalPages((int) historyDataPage.getPages());

            log.info("成功获取排污口监测弹框数据，当前数据{}条，历史数据{}条", 
                    currentData.size(), historyDataPage.getRecords().size());
        } catch (Exception e) {
            log.error("获取排污口监测弹框数据失败", e);
            throw new RuntimeException("获取排污口监测弹框数据失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 获取当前雷达图数据
     */
    private List<OutfallRadarDataVO> getCurrentRadarData() {
        // 定义企业颜色映射
        Map<String, String> enterpriseColors = new HashMap<>();
        enterpriseColors.put("新禹", "#00FF00");
        enterpriseColors.put("碧水", "#0000FF");

        // 查询所有正常状态的排污口
        LambdaQueryWrapper<EnterpriseOutfallValveInfo> outfallQuery = new LambdaQueryWrapper<>();
        outfallQuery.eq(EnterpriseOutfallValveInfo::getStatus, "1")
                   .orderByAsc(EnterpriseOutfallValveInfo::getCreateTime);

        List<EnterpriseOutfallValveInfo> outfalls = this.list(outfallQuery);
        List<OutfallRadarDataVO> radarDataList = new ArrayList<>();

        // 为每个企业获取最新监测数据
        for (EnterpriseOutfallValveInfo outfall : outfalls) {
            try {
                LambdaQueryWrapper<EnterpriseOutfallValve> dataQuery = new LambdaQueryWrapper<>();
                dataQuery.eq(EnterpriseOutfallValve::getOutfallId, outfall.getOutfallId())
                        .orderByDesc(EnterpriseOutfallValve::getMonitoringTime)
                        .last("LIMIT 1");

                EnterpriseOutfallValve latestData = enterpriseOutfallValveService.getOne(dataQuery,false);

                if (latestData != null) {
                    OutfallRadarDataVO radarData = new OutfallRadarDataVO();
                    radarData.setEnterpriseId(latestData.getCompanyId());
                    radarData.setEnterpriseName(latestData.getCompanyName());
                    radarData.setColor(enterpriseColors.getOrDefault(latestData.getCompanyName(), "#666666"));
                    radarData.setCodValue(latestData.getCodAvg());
                    radarData.setAmmoniaNitrogenValue(latestData.getAmmoniaNitrogenAvg());
                    radarData.setTotalPhosphorusValue(latestData.getTotalPhosphorusAvg());
                    radarData.setTotalNitrogenValue(latestData.getTotalNitrogenAvg());
                    radarData.setTotalCopperValue(latestData.getTotalCopperAvg());
                    radarData.setTotalChromiumValue(latestData.getTotalChromiumAvg());
                    radarData.setLastTime(latestData.getMonitoringTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    radarData.setTotalZincValue(latestData.getTotalZincAvg());
                    radarData.setPhValue(latestData.getPhAvg());
                    radarData.setFlowRateValue(latestData.getFlowRateAvg());
                    radarDataList.add(radarData);
                }
            } catch (Exception e) {
                log.warn("获取企业 {} 的雷达图数据失败: {}", outfall.getCompanyName(), e.getMessage());
            }
        }



        return radarDataList;
    }

    /**
     * 获取历史数据
     */
    private Page<OutfallMonitoringDataVO> getHistoryData(OutfallMonitoringQueryDTO queryDTO) {
        LambdaQueryWrapper<EnterpriseOutfallValve> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getEnterpriseName())) {
            query.eq(EnterpriseOutfallValve::getCompanyId, queryDTO.getEnterpriseName());
        }

        if (StringUtils.hasText(queryDTO.getStartTime())) {
            try {
                LocalDateTime startTime = LocalDateTime.parse(queryDTO.getStartTime() + " 00:00:00", 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                query.ge(EnterpriseOutfallValve::getMonitoringTime, startTime);
            } catch (Exception e) {
                log.warn("开始时间格式错误: {}", queryDTO.getStartTime());
            }
        }

        if (StringUtils.hasText(queryDTO.getStartTime())) {
            try {
                LocalDateTime endTime = LocalDateTime.parse(queryDTO.getStartTime() + " 23:59:59",
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                query.le(EnterpriseOutfallValve::getMonitoringTime, endTime);
            } catch (Exception e) {
                log.warn("结束时间格式错误: {}", queryDTO.getStartTime());
            }
        }

        query
             .orderByDesc(EnterpriseOutfallValve::getMonitoringTime);

        Page<EnterpriseOutfallValve> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<EnterpriseOutfallValve> dataPage = enterpriseOutfallValveService.page(page, query);

        Page<OutfallMonitoringDataVO> voPage = new Page<>(dataPage.getCurrent(), dataPage.getSize(), dataPage.getTotal());
        List<OutfallMonitoringDataVO> voList = dataPage.getRecords().stream().map(data -> {
            OutfallMonitoringDataVO vo = new OutfallMonitoringDataVO();
            BeanUtils.copyProperties(data, vo);
            vo.setCodValue(data.getCodAvg()!=null?data.getCodAvg().toString():"/");
            vo.setPhValue(data.getPhAvg()!=null?data.getPhAvg().toString():"/");
            vo.setFlowRateValue(data.getFlowRateAvg()!=null?data.getFlowRateAvg().toString():"/");
            vo.setTotalZincValue(data.getTotalZincAvg()!=null?data.getTotalZincAvg().toString():"/");
            vo.setTotalChromiumValue(data.getTotalChromiumAvg()!=null?data.getTotalChromiumAvg().toString():"/");
            vo.setTotalCopperValue(data.getTotalCopperAvg()!=null?data.getTotalCopperAvg().toString():"/");
            vo.setTotalNitrogenValue(data.getTotalNitrogenAvg()!=null?data.getTotalNitrogenAvg().toString():"/");
            vo.setTotalPhosphorusValue(data.getTotalPhosphorusAvg()!=null?data.getTotalPhosphorusAvg().toString():"/");
            vo.setAmmoniaNitrogenValue(data.getAmmoniaNitrogenAvg()!=null?data.getAmmoniaNitrogenAvg().toString():"/");
            vo.setEnterpriseName(data.getCompanyName());
            vo.setMonitoringTime(data.getMonitoringTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            return vo;
        }).collect(Collectors.toList());
        voPage.setRecords(voList);



        return voPage;
    }

    /**
     * 创建模拟雷达图数据
     */
    private List<OutfallRadarDataVO> createMockRadarData() {
        List<OutfallRadarDataVO> mockData = new ArrayList<>();

        // 新禹数据
        OutfallRadarDataVO xinyuData = new OutfallRadarDataVO();
        xinyuData.setEnterpriseName("新禹");
        xinyuData.setColor("#00FF00");
        xinyuData.setCodValue(new java.math.BigDecimal("0.001"));
        xinyuData.setAmmoniaNitrogenValue(new java.math.BigDecimal("0.001"));
        xinyuData.setTotalPhosphorusValue(new java.math.BigDecimal("0.001"));
        xinyuData.setTotalNitrogenValue(new java.math.BigDecimal("0.001"));
        xinyuData.setTotalCopperValue(new java.math.BigDecimal("0.001"));
        xinyuData.setTotalChromiumValue(new java.math.BigDecimal("0.001"));
        xinyuData.setTotalZincValue(new java.math.BigDecimal("0.001"));
        xinyuData.setPhValue(new java.math.BigDecimal("7.5"));
        xinyuData.setFlowRateValue(new java.math.BigDecimal("10.5"));
        mockData.add(xinyuData);

        // 碧水数据
        OutfallRadarDataVO bishuiData = new OutfallRadarDataVO();
        bishuiData.setEnterpriseName("碧水");
        bishuiData.setColor("#0000FF");
        bishuiData.setCodValue(new java.math.BigDecimal("0.001"));
        bishuiData.setAmmoniaNitrogenValue(new java.math.BigDecimal("0.001"));
        bishuiData.setTotalPhosphorusValue(new java.math.BigDecimal("0.001"));
        bishuiData.setTotalNitrogenValue(new java.math.BigDecimal("0.001"));
        bishuiData.setTotalCopperValue(new java.math.BigDecimal("0.001"));
        bishuiData.setTotalChromiumValue(new java.math.BigDecimal("0.001"));
        bishuiData.setTotalZincValue(new java.math.BigDecimal("0.001"));
        bishuiData.setPhValue(new java.math.BigDecimal("7.0"));
        bishuiData.setFlowRateValue(new java.math.BigDecimal("8.2"));
        mockData.add(bishuiData);

        // 超洁数据
        OutfallRadarDataVO chaojieData = new OutfallRadarDataVO();
        chaojieData.setEnterpriseName("超洁");
        chaojieData.setColor("#800080");
        chaojieData.setCodValue(new java.math.BigDecimal("0.02"));
        chaojieData.setAmmoniaNitrogenValue(new java.math.BigDecimal("0.02"));
        chaojieData.setTotalPhosphorusValue(new java.math.BigDecimal("0.02"));
        chaojieData.setTotalNitrogenValue(new java.math.BigDecimal("0.02"));
        chaojieData.setTotalCopperValue(new java.math.BigDecimal("0.02"));
        chaojieData.setTotalChromiumValue(new java.math.BigDecimal("0.02"));
        chaojieData.setTotalZincValue(new java.math.BigDecimal("0.02"));
        chaojieData.setPhValue(new java.math.BigDecimal("6.8"));
        chaojieData.setFlowRateValue(new java.math.BigDecimal("7.5"));
        mockData.add(chaojieData);

        return mockData;
    }

    /**
     * 创建模拟历史数据
     */
    private Page<OutfallMonitoringDataVO> createMockHistoryData(OutfallMonitoringQueryDTO queryDTO) {
        Page<OutfallMonitoringDataVO> mockPage = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize(), 400L);

        List<OutfallMonitoringDataVO> mockData = new ArrayList<>();

        // 模拟数据
        OutfallMonitoringDataVO data1 = new OutfallMonitoringDataVO();
        data1.setEnterpriseName("武义县新禹水处理有限公司");
//        data1.setMonitoringTime(LocalDateTime.parse("2025-07-01T00:00:00"));

        mockData.add(data1);

        mockPage.setRecords(mockData);
        return mockPage;
    }
}